<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Vip as VipModel;
use app\user\model\Money as MoneyModel;
use app\user\model\Rebate as RebateModel;
use app\user\model\Level;
use util\Tree;
use think\facade\Db;

/**
 * 资金流水控制器
 * @package app\user\admin
 */
class Money extends Admin
{
    /**
     * 流水列表
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index($id = 0, $uid = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
		
		$search_field = [];
		if ($id > 0) {
			$map[] = ['id', '=', $id];
		}
		
		if ($uid > 0) {
			$map[] = ['uid', '=', $uid];
		}
		if ($uid == 0 && $id == 0) {
			$search_field = ['user_vip.member_id' => '会员ID',  'user_vip.realname' => '姓名', 'user_vip.mobile' => '手机号'];
		}
		
		// 排序条件
		$order = $this->getOrder('create_time desc');
		
        // 数据列表
        $data_list = MoneyModel::getList($map, $order);
//                var_dump($data_list);exit;
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('Vip管理') // 设置页面标题
            ->setSearch($search_field) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['uid', '会员ID'],
                ['realname', '姓名'],
                ['mobile', '手机号'],
				['group', '会员等级', 'callback', function($value){return Level::level_list($value);}],
				['type', '变动方式', 'status', '', MoneyModel::type()],
				['balance', '首购变动', 'callback', function($value){return '￥'. $value / 100 ;}],
				['second', '复购变动', 'callback', function($value){return '￥'. $value / 100 ;}],
				['realpay', '现金支付', 'callback', function($value){return '￥'. $value / 100 ;}],
				['money', '首单余额', 'callback', function($value){return '￥'. $value / 100 ;}],
				['money_se', '复购余额', 'callback', function($value){return '￥'. $value / 100 ;}],
                ['create_time', '时间', 'datetime'],
				['remark', '备注', 'popover', 5],
            ])
            ->setRowList($data_list) // 设置表格数据
			->addFilterList('group', Level::level_list())
			->addFilterList('type', MoneyModel::type())
            ->fetch(); // 渲染页面
    }
	
    /**
     * 导出
     * @param null $id 用户id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay($id = null)
    {
        if ($id === null) $this->error('缺少参数');
    
        // 保存数据
        if ($this->request->isAjax()) {
            $take = MoneyTakeModel::where('id', '=', $id)->find();
			if ($take) {
				if($take['status'] < 1) $this->error('请先同意申请');
				if($take['status'] > 1) $this->error('该申请已提现完成');
				$vip = VipModel::where('member_id', '=', $take['uid'])->find();
				if(!$vip) $this->error('会员信息错误');
				if ($vip['money_take'] < $take['money_take']) $this->error('可提现余额少于￥'.$take['money_take']/100);
				$money_take = $vip['money_take'];
				$vip->money_take = ['dec', $take['money_take']];
				if ($vip->save()) {
					$take->status = 2;
					$take->save();
					$save_data = [
						'uid'		=> $take['uid'],
						'type'		=> 3,
						'model'		=> 3,
						'money'		=> -$take['money_take'],
						'pre'		=> 100,
						'pay'		=> -$take['money_take'],
						'from_uid'	=> $take['uid'],
						'oid'		=> $id,
						'money_take'=> $money_take - $take['money_take'],
					];
					RebateModel::create($save_data);
					$this->success('提现完成');
				} else {
					$this->error('提现失败');
				}
			} else {
				$this->error('未找到该提现申请');
			}
        }
    }   
    
    /**
     * 删除Vip用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($ids = [])
    {
		$ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		$delete = MoneyTakeModel::where('id', 'in', $ids)->where('status', '=', 0)->delete();
        if ($delete) {
			$this->success('撤销成功');
		} else {
			$this->error('只能撤销待同意的申请');
		}
    }

    /**
     * 启用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置产品状态：删除、禁用、启用
     * @param string $type 类型：enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		$status = 0;
		if ($type == 'enable') {
			$status = 1;
		}
        $update = MoneyTakeModel::where('id', 'in', $ids)->where('status', '<>', 2)->update(['status' => $status, 'admin' => UID]);
		if ($update) {
			$this->success('操作成功');
		} else {
			$this->error('操作失败');
		}
        // return parent::setStatus($type, ['vip_'.$type, 'user_vip', 0, UID, implode('、', $realname)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');

        $config  = MoneyTakeModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['money_take', 'user_money_take', $id, UID, $details]);
    }
}
